package jd.se.book;

import jd.se.common.CurrentUser;
import jd.se.common.Utils;
import org.apache.ibatis.session.SqlSession;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BookService {
    public Map<String,Object> getBookList(QueryDto queryDto) {

        SqlSession sess = Utils.openSession();

        try{
            BookDao dao = sess.getMapper(BookDao.class);
            //执行映射器方法之前立即执行分页参数（页码和每页记录数）的设置
            PageHelper.startPage(queryDto);
            List<Book> BookList = dao.findBookList(queryDto);
            //执行映射器方法之后，立即执行PageInfo对象的创建
            PageInfo<Book> pageInfo = new PageInfo<>(BookList);

            Map<String,Object> page = new HashMap<>();
            page.put("current", pageInfo.getPageNum());//当前页
            page.put("pageSize",pageInfo.getPageSize());//每页最大记录数
            page.put("total",pageInfo.getTotal());//总记录数
            page.put("pages",pageInfo.getPages());//总页数
            page.put("size",pageInfo.getSize());//当前页实际记录数
            page.put("list",pageInfo.getList());//当前页的数据记录
            page.put("first",1);
            page.put("pre",pageInfo.getPrePage());
            page.put("next",pageInfo.getNextPage());
            page.put("last",pageInfo.getPages());


            sess.commit();

            return page;

        }catch(Exception e){
            sess.rollback();
            throw new RuntimeException("查询书籍信息失败！",e);
        }finally {
            sess.close();
        }
    }

    public void addborrow_info(BorrowDto dto, CurrentUser currentUser) {
        dto.setCurrent_id(currentUser.getUserId());
        SqlSession sess = Utils.openSession();
        try{
            BookDao dao = sess.getMapper(BookDao.class);
            Timestamp day = new Timestamp(System.currentTimeMillis());
            dto.setCurrent_date(day.toString());
            dao.insertinfo(dto);
            sess.commit();
        }catch(Exception e){
            sess.rollback();
            throw new RuntimeException("申请失败！",e);
        }finally {
            sess.close();
        }
    }
}

